package com.yisu.expressway.api.web.controller;

import com.google.common.collect.Lists;
import com.google.gson.JsonObject;
import com.pingplusplus.Pingpp;
import com.pingplusplus.exception.*;
import com.pingplusplus.model.Charge;
import com.pingplusplus.model.Refund;
import com.yisu.expressway.api.core.service.IGoodsInfoService;
import com.yisu.expressway.api.core.service.IOrderService;
import com.yisu.expressway.api.domain.config.SystemConfig;
import com.yisu.expressway.api.domain.request.GoodsInfoRequest;
import com.yisu.expressway.api.domain.request.PingXXChargeResponse;
import com.yisu.expressway.api.domain.request.orderModule.*;
import com.yisu.expressway.api.domain.response.CreateOrderResponse;
import com.yisu.expressway.api.domain.response.OrderDetailResponse;
import com.yisu.expressway.api.domain.response.OrderListResponse;
import com.yisu.expressway.api.domain.response.OrderStatusNumResponse;
import com.yisu.expressway.api.domain.vo.GoodsDetailVo;
import com.yisu.expressway.api.domain.vo.OrderGoodsRequestVo;
import com.yisu.expressway.api.domain.vo.orderModule.OrderMainVo;
import com.yisu.expressway.api.domain.vo.orderModule.OrderStatusNumVo;
import com.yisu.expressway.api.domain.vo.orderModule.OrderSubVo;
import com.yisu.expressway.api.web.interceptor.IAuthVerifyAnnotation;
import com.yisu.expressway.ewf.common.enums.ResponseCode;
import com.yisu.expressway.ewf.common.web.HttpWebClient;
import com.yisu.expressway.ewf.common.web.JsonResult;
import com.yisu.expressway.ewf.entity.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.yisu.expressway.ewf.common.enums.ResponseCode.FAILURE;
import static com.yisu.expressway.ewf.common.enums.ResponseCode.SUCCESS;

/**
 * 订单业务处理
 * Created by zj on 2017/5/4.
 */
@RequestMapping("/order")
@Controller
public class OrderController extends BaseController {
    @Resource
    private IOrderService iOrderService;
    @Resource
    private IGoodsInfoService iGoodsInfoService;
    @Resource
    private SystemConfig systemConfig;

    /**
     * 获取模块数据
     *
     * @param token              token令牌， 可为空
     * @param createOrderRequest
     * @return json响应
     */
    @RequestMapping(value = "/createOrder", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证")
    public JsonResult createOrder(@RequestHeader(value = "X-Long-Token", required = false) String token, @RequestBody CreateOrderRequest createOrderRequest) {
        JsonResult result = new JsonResult();
        CreateOrderResponse createOrderReponse = new CreateOrderResponse();
        try {
            if (StringUtils.isEmpty(createOrderRequest.getConsigneeAccount()) || StringUtils.isEmpty(createOrderRequest.getConsigneeAddress()) || StringUtils.isEmpty(createOrderRequest.getConsigneeArea())
                    || StringUtils.isEmpty(createOrderRequest.getConsigneeCity()) || StringUtils.isEmpty(createOrderRequest.getConsigneeName())
                    || StringUtils.isEmpty(createOrderRequest.getConsigneeProvince()) || CollectionUtils.isEmpty(createOrderRequest.getOrderGoodsRequestVos())) {
                return new JsonResult(ResponseCode.PARAMETER_ERROR.code, "参数不完整！");
            }
            User user = this.getUserByToken(token);
            OrderMain orderMain = new OrderMain();
            List<OrderSub> orderSubs = Lists.newArrayList();
            int tradeType = 0;
            BigDecimal totalPrice = BigDecimal.valueOf(0);
            //校验购买的商品
            for (OrderGoodsRequestVo goodsItem : createOrderRequest.getOrderGoodsRequestVos()) {
                GoodsInfoRequest goodsInfoRequest = new GoodsInfoRequest();
                goodsInfoRequest.setCategoryCode(goodsItem.getCategoryCode());
                goodsInfoRequest.setSpecificationNo(goodsItem.getSpecificationNo());
                goodsInfoRequest.setGoodsNo(goodsItem.getGoodsNo());
                SpecificationGoods specificationGoods = iOrderService.getSpecificationGoods(goodsInfoRequest);
                if (specificationGoods == null) {
                    return new JsonResult(ResponseCode.FAILURE.code, "当前商品已过期，请刷新！");
                }
                if (specificationGoods.getInventoryNum() < goodsItem.getBuyNumber()) {
                    return new JsonResult(ResponseCode.FAILURE.code, "库存不足");
                }
                GoodsDetailVo goodsDetailVo = iGoodsInfoService.getGoodsDetail(goodsInfoRequest);
                if (goodsDetailVo == null) {
                    return new JsonResult(ResponseCode.FAILURE.code, "当前商品已过期，请刷新！");
                }
                OrderSub orderSub = new OrderSub();
                orderSub.setGoodsNo(goodsDetailVo.getGoodsNo());
                orderSub.setCategoryCode(Long.valueOf(goodsDetailVo.getCategoryCode()));
                orderSub.setSpecificationNo(goodsDetailVo.getSpecificationNo());
                orderSub.setName(goodsDetailVo.getName());
                orderSub.setSecondName(goodsDetailVo.getSecondName());
                orderSub.setProductName(goodsDetailVo.getProductName());
                orderSub.setProductCode(goodsDetailVo.getProductCode());
                orderSub.setBrand(goodsDetailVo.getBrand());
                orderSub.setSpecificationName(goodsDetailVo.getSpecificationName());
                orderSub.setProducingArea(goodsDetailVo.getProducingArea());
                orderSub.setTallageDesc(goodsDetailVo.getTallageDesc());
                orderSub.setPrivilegeDesc(goodsDetailVo.getPrivilegeDesc());
                orderSub.setTallageDesc(goodsDetailVo.getTallageDesc());
                orderSub.setTradeType(goodsDetailVo.getTradeType());
                if (goodsDetailVo.getTradeType() == 1)
                    tradeType = 1;
                orderSub.setMarketTime(goodsDetailVo.getMarketTime());
                orderSub.setImage(goodsDetailVo.getImage());
                orderSub.setDetailsInfo(goodsDetailVo.getDetailsInfo());
                orderSub.setBazaarPrice(goodsDetailVo.getBazaarPrice());
                orderSub.setPrice(goodsDetailVo.getPrice());
                orderSub.setBuyNumber(goodsItem.getBuyNumber());
                orderSub.setTotalPrice(goodsDetailVo.getPrice().multiply(new BigDecimal(goodsItem.getBuyNumber())));
                orderSub.setTaxRateDesc(goodsDetailVo.getTaxRateDesc());
                totalPrice = orderSub.getTotalPrice().add(totalPrice);
                orderSubs.add(orderSub);
            }
            orderMain.setUserAccount(user.getUserAccount());
            orderMain.setUserName(user.getUserName());
            orderMain.setOrderStatus(OrderMain.OrderStatus.WAIT_PAY.code);//等待支付
            orderMain.setOrderAmount(totalPrice);
            orderMain.setGoodsAllAmount(totalPrice);
            orderMain.setDiscountAmount(BigDecimal.valueOf(0));
            orderMain.setOrderAbstract("");
            orderMain.setConsigneeAccount(createOrderRequest.getConsigneeAccount());
            orderMain.setConsigneeName(createOrderRequest.getConsigneeName());
            orderMain.setConsigneeProvince(createOrderRequest.getConsigneeProvince());
            orderMain.setConsigneeCity(createOrderRequest.getConsigneeCity());
            orderMain.setConsigneeArea(createOrderRequest.getConsigneeArea());
            orderMain.setConsigneeAddress(createOrderRequest.getConsigneeAddress());
            orderMain.setTradeType(tradeType);
            if (orderMain.getTradeType().equals(1)) {
                if (StringUtils.isEmpty(createOrderRequest.getConsigneeIdNumber())) {
                    return new JsonResult(ResponseCode.FAILURE.code, "进口商品，身份证必填！");
                } else {
                    orderMain.setConsigneeIdNumber(createOrderRequest.getConsigneeIdNumber());
                }
            }
            long orderId = iOrderService.addOrder(orderMain, orderSubs);
            if (orderId <= 0) {
                return new JsonResult(ResponseCode.FAILURE.code, "网络君泡妞去了！");
            }
            SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            createOrderReponse.setCurrentSystemTime(sformat.format(new java.util.Date()));
            Calendar nowTime = Calendar.getInstance();
            nowTime.add(Calendar.MINUTE, systemConfig.getPaymentDeadlineTime());
            createOrderReponse.setPaymentDeadlineTime(sformat.format(nowTime.getTime()));
            createOrderReponse.setOrderId(orderId);
            return new JsonResult(createOrderReponse);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new JsonResult(ResponseCode.FAILURE.code, "网络君泡妞去了！");
    }

    /**
     * 获取订单详情
     *
     * @param token              token令牌， 可为空
     * @param orderDetailRequest
     * @return json响应
     */
    @RequestMapping(value = "/getOrderDetail", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证")
    public JsonResult getOrderDetail(@RequestHeader(value = "X-Long-Token", required = false) String token, @RequestBody OrderDetailRequest orderDetailRequest) {
        JsonResult result = new JsonResult();
        OrderDetailResponse orderDetailResponse = new OrderDetailResponse();
        OrderMainVo orderMainVo = new OrderMainVo();
        try {
            if (orderDetailRequest.getOrderId() == null) {
                return new JsonResult(ResponseCode.PARAMETER_ERROR.code, "参数不完整！");
            }
            OrderMain orderMain = iOrderService.getOrderMainByOrderId(orderDetailRequest.getOrderId());
            if (orderMain != null) {

                SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                orderMainVo = convertOrderModel(orderMain, sformat);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        orderDetailResponse.setOrderMainVo(orderMainVo);
        result.setData(orderDetailResponse);
        return result;
    }

    /**
     * 确认收货
     *
     * @param token token令牌， 可为空
     * @return json响应
     */
    @RequestMapping(value = "/confirmDeliveryGoods", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证")
    public JsonResult confirmDeliveryGoods(@RequestHeader(value = "X-Long-Token", required = false) String token, @RequestBody OrderInfoRequest orderInfoRequest) {
        JsonResult result = new JsonResult();
        try {
            if (orderInfoRequest.getOrderId() == null) {
                return new JsonResult(ResponseCode.PARAMETER_ERROR.code, "参数不完整！");
            }
            User user = this.getUserByToken(token);
            OrderMain orderMain = iOrderService.getOrderMainByOrderId(orderInfoRequest.getOrderId());
            if (!orderMain.getUserAccount().equals(user.getUserAccount())) {
                return new JsonResult(FAILURE.code, "不可非法操作！");
            }
            if (orderMain.getOrderStatus() < 20) {
                return new JsonResult(FAILURE.code, "不可非法操作！");
            }
            orderMain.setOrderStatus(100);
            if (iOrderService.updateOrderUpdate(orderMain)) {
                return new JsonResult();
            } else {
                return new JsonResult(FAILURE.code, "操作失败！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * 取消订单
     *
     * @param token token令牌， 可为空
     * @return json响应
     */
    @RequestMapping(value = "/cancelOrder", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证")
    public JsonResult cancelOrder(@RequestHeader(value = "X-Long-Token", required = false) String token, @RequestBody OrderInfoRequest orderInfoRequest) {
        JsonResult result = new JsonResult();
        try {
            if (orderInfoRequest.getOrderId() == null) {
                return new JsonResult(ResponseCode.PARAMETER_ERROR.code, "参数不完整！");
            }
            User user = this.getUserByToken(token);
            OrderMain orderMain = iOrderService.getOrderMainByOrderId(orderInfoRequest.getOrderId());
            if (!orderMain.getUserAccount().equals(user.getUserAccount())) {
                return new JsonResult(FAILURE.code, "不可非法操作！");
            }
            orderMain.setOrderStatus(-100);
            if (iOrderService.cancelOrder(orderInfoRequest.getOrderId())) {
                return new JsonResult();
            } else {
                return new JsonResult(FAILURE.code, "操作失败！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }


    /**
     * 获取订单各状态数量
     *
     * @param token token令牌， 可为空
     * @return json响应
     */
    @RequestMapping(value = "/getOrderStatusNum", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证")
    public JsonResult getOrderStatusNum(@RequestHeader(value = "X-Long-Token", required = false) String token) {
        JsonResult result = new JsonResult();
        OrderStatusNumResponse orderStatusNumResponse = new OrderStatusNumResponse();
        OrderStatusNumVo orderStatusNumVo = new OrderStatusNumVo();
        try {
            User user = this.getUserByToken(token);
            orderStatusNumVo = iOrderService.getOrderStatusNumByUserAccount(user.getUserAccount());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        orderStatusNumResponse.setOrderStatusNumVo(orderStatusNumVo);
        result.setData(orderStatusNumResponse);
        return result;
    }

    /**
     * 发货消息推送方法
     * @param orderAmount 订单金额
     */
    protected void notifyPush(BigDecimal orderAmount){
        try {
            List<String> openIds=Lists.newArrayList("oeOEsw0rrRqdBLA4Q7fxzw_nLQAg","oeOEswzsn33bPXIimZmevRRxTx5E");
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime =dateFormat.format(date);
            for(String item:openIds)
            {
                JsonObject body = new JsonObject();
                body.addProperty("openId",item);//公司运营公众号openID,暂时写死
                body.addProperty("pushTitle","有新订单进来，请尽快安排发货哦");
                body.addProperty("keyword1","杭州驿速网络科技");
                body.addProperty("keyword2",orderAmount+"");
                body.addProperty("keyword3",currentTime);
                body.addProperty("remark","感谢您对杭州驿速网络科技的支持，客服电话：40060052");
                Map<String, String> headerMap = new HashMap<>();
                headerMap.put("Content-type", "application/json; charset=utf-8");
                headerMap.put("Accept", "application/json");
                headerMap.put("X-Client-Agent", "User-Agent: ExpressWay/2.0.1 (com.yisu.expressway; build:175; iOS 10.1.1) Alamofire/3.5.1");
                headerMap.put("User-Agent", "ExpressWay/2.0.1 (com.yisu.expressway; build:175; iOS 10.1.1) Alamofire/3.5.1");
                headerMap.put("X-APIVersion", "1.0");
                headerMap.put("X-Long-Token", "4eed7fc046d2411b9263029b3dbcf23e");//88eeab5ee8b94a8ab8ff552e94967ba7, dbf4841e2ba84569ac276c4a167421a7 b1a41ff3e58b45318f605cc0bccea40f 469213d3d2154175a5bbc49945f2843e
                headerMap.put("X-Client-ID", "12369812111454545454534545");
                HttpWebClient.postJsonBody(systemConfig.getNotifyPushUrl(), headerMap, body.toString());
                logger.info("待发货推送消息发送成功=========================="+item);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/PingNotify", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult PingNotify(PaySuccessRequest paySuccessRequest) {
        if (paySuccessRequest.getOrderId() == null || StringUtils.isEmpty(paySuccessRequest.getPayId()) || StringUtils.isEmpty(paySuccessRequest.getSecretKey())) {
            return new JsonResult(ResponseCode.PARAMETER_ERROR.code, "参数不完整！");
        }
        if (!paySuccessRequest.getSecretKey().equals("6ed71d1d9e4bc0aea5d5bbf4fe032333")) {
            return new JsonResult(ResponseCode.FAILURE.code, "非法请求！");
        }
        OrderMain orderMain = iOrderService.getOrderMainByOrderId(paySuccessRequest.getOrderId());
        if (orderMain != null) {
            if (orderMain.getOrderStatus().equals(OrderMain.OrderStatus.WAIT_DELIVER_GOODS.code)) {
                return new JsonResult(SUCCESS.code, "操作成功！");
            }
            if (iOrderService.paySuccess(paySuccessRequest)) {
                OrderMain pushMegJust = iOrderService.getOrderMainByOrderId(paySuccessRequest.getOrderId());
                if (pushMegJust.getOrderStatus().equals(OrderMain.OrderStatus.WAIT_DELIVER_GOODS.code)) {
                    notifyPush(orderMain.getOrderAmount());
                }
                return new JsonResult(SUCCESS.code, "操作成功！");
            } else {
                return new JsonResult(FAILURE.code, "操作失败！");
            }
        }
        return new JsonResult(FAILURE.code, "操作失败！");
    }


    /**
     * 公用转换model
     *
     * @param orderMain 订单主信息
     * @param sformat   时间格式转换
     * @return OrderListForMainVo
     */
    protected OrderMainVo convertOrderModel(OrderMain orderMain, SimpleDateFormat sformat) {
        OrderMainVo orderMainVo = new OrderMainVo();
        orderMainVo.setUserAccount(orderMain.getUserAccount());
        orderMainVo.setOrderId(orderMain.getOrderId());
        orderMainVo.setCreateTime(sformat.format(orderMain.getCreateTime()));
        orderMainVo.setOrderAmount(orderMain.getOrderAmount());
        orderMainVo.setGoodsAllAmount(orderMain.getGoodsAllAmount());
        orderMainVo.setUserName(orderMain.getUserName());
        orderMainVo.setOrderStatus(orderMain.getOrderStatus());
        orderMainVo.setOrderStatusDesc(OrderMain.OrderStatus.getEnumNameByCode(orderMain.getOrderStatus()));
        if (orderMain.getTradeType() != null) {
            orderMainVo.setTradeTypeDesc(OrderMain.TradeTypeEnum.getEnumNameByCode(orderMain.getTradeType()));
        }
        if (orderMain.getPayType() != null) {
            orderMainVo.setPayTypeDesc(OrderMain.PayType.getEnumNameByCode(orderMain.getPayType()));
        }
        orderMainVo.setConsigneeAccount(orderMain.getConsigneeAccount());
        orderMainVo.setConsigneeIdNumber(orderMain.getConsigneeIdNumber());
        orderMainVo.setConsigneeAddress(orderMain.getConsigneeAddress());
        orderMainVo.setConsigneeArea(orderMain.getConsigneeArea());
        orderMainVo.setConsigneeCity(orderMain.getConsigneeCity());
        orderMainVo.setConsigneeName(orderMain.getConsigneeName());
        orderMainVo.setConsigneeProvince(orderMain.getConsigneeProvince());
        //添加订单子表信息
        List<OrderSubVo> orderSubVos = Lists.newArrayList();
        List<OrderSub> orderSubList = iOrderService.getOrderSubListByOrderId(orderMain.getOrderId());
        if (!CollectionUtils.isEmpty(orderSubList)) {
            for (OrderSub orderSub : orderSubList) {
                OrderSubVo orderSubVo = new OrderSubVo();
                orderSubVo.setName(orderSub.getName());
                orderSubVo.setSpecificationName(orderSub.getSpecificationName());
                orderSubVo.setOrderId(orderSub.getOrderId());
                orderSubVo.setBazaarPrice(orderSub.getBazaarPrice());
                orderSubVo.setBrand(orderSub.getBrand());
                orderSubVo.setBuyNumber(orderSub.getBuyNumber());
                orderSubVo.setSpecificationNo(orderSub.getSpecificationNo());
                orderSubVo.setSecondName(orderSub.getSecondName());
                orderSubVo.setGoodsNo(orderSub.getGoodsNo());
                orderSubVo.setCategoryCode(orderSub.getCategoryCode());
                orderSubVo.setImage(orderSub.getImage());
                orderSubVo.setPrice(orderSub.getPrice());
                orderSubVo.setTradeTypeDesc(OrderMain.TradeTypeEnum.getEnumNameByCode(orderSub.getTradeType()));
                orderSubVos.add(orderSubVo);
            }
        }
        orderMainVo.setOrderSubVos(orderSubVos);
        return orderMainVo;
    }

    /**
     * 获取订单列表
     *
     * @param token            token令牌， 可为空
     * @param orderListRequest
     * @return json响应
     */
    @RequestMapping(value = "/getOrderList", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证")
    public JsonResult getOrderList(@RequestHeader(value = "X-Long-Token", required = false) String token, @RequestBody OrderListRequest orderListRequest) {
        JsonResult result = new JsonResult();
        OrderListResponse orderListResponse = new OrderListResponse();
        List<OrderMainVo> orderMainVos = Lists.newArrayList();
        SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            User user = this.getUserByToken(token);
            orderListRequest.setUserAccount(user.getUserAccount());
            List<OrderMain> orderMainList = iOrderService.getUserOrderMainList(orderListRequest);
            if (!CollectionUtils.isEmpty(orderMainList)) {
                for (OrderMain orderMainItem : orderMainList) {
                    OrderMainVo orderMainVo = new OrderMainVo();
                    orderMainVo = convertOrderModel(orderMainItem, sformat);
                    orderMainVos.add(orderMainVo);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        orderListResponse.setOrderMainVos(orderMainVos);
        result.setData(orderListResponse);
        return result;
    }


    /**
     * 订单退款操作
     *
     * @param orderRefundRequest 请求参数
     * @return 状态
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/orderRefund", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult orderRefund(OrderRefundRequest orderRefundRequest) throws UnsupportedEncodingException, RateLimitException, APIException, ChannelException, InvalidRequestException, APIConnectionException, AuthenticationException {
        Refund re = null;
        Charge charge = null;
        try {
            if (orderRefundRequest.getOrderId() == 0 || orderRefundRequest.getOrderRefundId() == 0) {
                return new JsonResult(ResponseCode.PARAMETER_ERROR.code, "参数不完整！");
            }
            OrderMain orderInfo = iOrderService.getOrderMainByOrderId(orderRefundRequest.getOrderId());
            if (orderInfo == null) {
                return new JsonResult(FAILURE.code, "当前订单出现异常，不可操作退款");
            }
            //获取有效退款流水记录
            RefundRecord refundRecord = iOrderService.getRefundRecordByPrimaryKey(orderRefundRequest.getOrderRefundId());
            if (orderInfo.getOrderStatus() != OrderMain.OrderStatus.CANCEL_WAIT_PAY.code) {
                return new JsonResult(FAILURE.code, "订单当前不可进行退款操作");
            }
            if (orderInfo.getOrderAmount().compareTo(refundRecord.getRefundAmount()) < 0) {
                return new JsonResult(FAILURE.code, "非法退款，禁止操作！");
            }
            if (refundRecord == null) {
                return new JsonResult(FAILURE.code, "非法退款，禁止操作！");
            }
            Pingpp.apiKey = "sk_live_H40a10vf5ib994iXHOKmzXDG";
            java.net.URL uri = Thread.currentThread().getContextClassLoader().getResource("");
            String path = URLDecoder.decode(uri.getPath(), "UTF-8") + "pingxx.pem";
            Pingpp.privateKeyPath = path;
            charge = Charge.retrieve(orderInfo.getPayOrderId());//ch_id 是已付款的订单号
            Map<String, Object> refundMap = new HashMap<String, Object>();
            refundMap.put("amount", orderInfo.getOrderAmount().multiply(BigDecimal.valueOf(100)));
            refundMap.put("description", refundRecord.getReason());
            re = charge.getRefunds().create(refundMap);
            if (re != null && StringUtils.isEmpty(re.getFailureMsg())) {
                RefundRecord updateModel = new RefundRecord();
                updateModel.setId(refundRecord.getId());
                updateModel.setStatus(RefundRecord.StatusEnum.SUCCESS.code);
                updateModel.setRefundObjId(re.getOrderNo());
                updateModel.setRefundNo(re.getId());
                updateModel.setOrderId(orderInfo.getOrderId());
                updateModel.setRefundTime(new java.sql.Timestamp(new java.util.Date().getTime()));
                if (!StringUtils.isEmpty(orderRefundRequest.getReason())) {
                    updateModel.setReason(orderRefundRequest.getReason());
                }
                iOrderService.refundSuccess(updateModel);
                return new JsonResult();
            }
        } catch (Exception ex) {
            return new JsonResult(FAILURE.code, "退款失败：" + ex.getMessage());
        }
        return new JsonResult(FAILURE.code, "退款失败");
    }


    /**
     * 获取支付方式支付数据
     *
     * @param orderPaymentRequest 请求参数
     * @return 支付charge
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/getPaymentData", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult getPaymentData(@RequestBody OrderPaymentRequest orderPaymentRequest) throws UnsupportedEncodingException {
        try {
            OrderMain orderInfo = iOrderService.getOrderMainByOrderId(orderPaymentRequest.getOrderId());
            if (orderInfo.getOrderStatus() == OrderMain.OrderStatus.CANCEL_ORDER.code) {
                logger.error("订单已取消", FAILURE.code, FAILURE.msg);
                return new JsonResult(FAILURE.code, "订单已取消");
            }
            if (orderInfo.getOrderStatus() != OrderMain.OrderStatus.WAIT_PAY.code) {
                logger.error("订单已支付", FAILURE.code, FAILURE.msg);
                return new JsonResult(FAILURE.code, "订单已支付");
            }
            Charge charge = null;
            Pingpp.apiKey = "sk_live_H40a10vf5ib994iXHOKmzXDG";
            java.net.URL uri = Thread.currentThread().getContextClassLoader().getResource("");
            String path = URLDecoder.decode(uri.getPath(), "UTF-8") + "pingxx.pem";
            Pingpp.privateKeyPath = path;
            Map<String, Object> chargeParams = new HashMap<String, Object>();
            chargeParams.put("order_no", orderInfo.getOrderId());
            chargeParams.put("amount", orderInfo.getOrderAmount().multiply(BigDecimal.valueOf(100)));
            Map<String, String> app = new HashMap<String, String>();
            app.put("id", "app_WPqLGCDy1Ki10K0K");
            chargeParams.put("app", app);
            chargeParams.put("currency", "cny");
            chargeParams.put("client_ip", GetIp());
            String subject = "订单支付：" + orderInfo.getOrderId();
            chargeParams.put("subject", subject);
            String desc = "订单支付：" + orderInfo.getOrderId();
            chargeParams.put("body", desc);
            chargeParams.put("description", "mallOrder");
            chargeParams.put("time_expire", DateTime.now().plusMinutes(10).getMillis() / 1000);
            switch (orderPaymentRequest.getPaymentChannel()) {
                case 1://alipay PaymentType.Alipay.code
                    chargeParams.put("channel", "alipay");
                    break;
                case 2: // 微信
                    chargeParams.put("channel", "wx");
                    break;
                case 3://微信支付
                    chargeParams.put("channel", "wx_pub");
                    Map<String, Object> extra = new HashMap<String, Object>();
                    extra.put("open_id", orderInfo.getUserAccount());//oeOEsw8-IAP2n-gvBm2fgGa611Hg
                    chargeParams.put("extra", extra);
                    break;
            }
            //发起交易请求
            charge = Charge.create(chargeParams);
            ChangeOrderPaymentRequest changeOrderPaymentRequest = new ChangeOrderPaymentRequest();
            changeOrderPaymentRequest.setOrderId(orderInfo.getOrderId());
            changeOrderPaymentRequest.setPaymentMethod(orderPaymentRequest.getPaymentChannel());
            iOrderService.changeOrderPayment(changeOrderPaymentRequest);
            JsonResult result = new JsonResult();
            PingXXChargeResponse pingXXChargeResponse = new PingXXChargeResponse();
            pingXXChargeResponse.setChargeObj(charge.toString());
            result.setData(pingXXChargeResponse);
            return result;
        } catch (Exception ex) {
            return new JsonResult(FAILURE.code, "error:" + ex.toString());
        }
       /* return new JsonResult(FAILURE.code, "网络君泡妞去了....");*/
    }

    private static String GetIp() {
        InetAddress ia = null;
        try {
            ia = ia.getLocalHost();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ia.getHostAddress();
    }


    /**
     * 取消未支付的订单
     *
     */
    @RequestMapping(value = "/cancelOrderForJob", method = {RequestMethod.GET}, produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult cancelOrderForJob() {
        if(iOrderService.cancelOrderForJob()) {
            return new JsonResult();
        }

        return new JsonResult(ResponseCode.FAILURE.code, ResponseCode.FAILURE.msg);
    }


    /**
     * 确认收货
     *
     */
    @RequestMapping(value = "/confirmOrder", method = {RequestMethod.GET}, produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult confirmOrder() {
        iOrderService.confirmOrder();
        return new JsonResult();
    }

}
